<template>
  <table>
    <tr>
      <th></th>
      <th v-for="column in columns" :key="column">
        {{ column }}
      </th>
    </tr>
    <tr v-for="(row, index) in matrix" :key="index">
      <td class="row-label">{{ rows[index] }}</td>
      <td v-for="(cell, index) in row" :key="index">
        <div class="column" v-if="cell">
          <slot v-bind:cell="cell">
          </slot>
        </div>
      </td>
    </tr>
  </table>
</template>

<script>
export default {
  name: "DataMatrix",
  props: {
    data: {
      type: Array,
      default: () => []
    },
    rowField: {
      type: String,
      default: 'row'
    },
    columnField: {
      type: String,
      default: 'column'
    },
    rows: {
      type: Array,
      default: () => []
    },
    columns: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      matrix: []
    }
  },
  created() {
    this.flushData()
  },
  watch: {
    data() {
      this.flushData()
    }
  },
  methods: {
    flushData() {
      this.matrix = new Array(this.rows.length);
      // console.log(this.matrix)
      for (let i = 0; i < this.matrix.length; i++) {
        this.matrix[i] = new Array(this.columns.length)
      }
      this.data.forEach((item) => {
        // console.log(item)
        this.matrix[item[this.rowField]-1][item[this.columnField]-1] = item
      })
      // console.log(this.matrix)
    }
  }
}
</script>

<style scoped>
table {
  border-collapse: collapse;
}

table tr th {
  border: 1px solid #dcdfe6;
  background: #F2F6FC;
  padding: 10px 0;
}

table tr td {
  border: 1px solid #dcdfe6;
  background: #F2F6FC;
  width: 160px;
  height: 85px;
}

td.row-label {
  text-align: center;
}

.column {
  text-align: center;
  width: 100%;
  height: 100%;
}
</style>